import {
  Component,
  ViewChild
} from '@angular/core';
import {
  Platform,
  Events,
  Nav,
  IonicApp,
  Keyboard,
  ToastController, ViewController
} from 'ionic-angular';
import {
  StatusBar
} from '@ionic-native/status-bar';
import {
  SplashScreen
} from '@ionic-native/splash-screen';
import {
  IndexPage
} from '../pages/index/index';
import {
  TabsPage
} from '../pages/tabs/tabs';
import {
  Storage,
} from '@ionic/storage'
import {
  Http,
  Headers,
  RequestOptions,
  URLSearchParams
} from '@angular/http';
import {
  AppConfig
} from '../app/app.config';
import {
  Geolocation
} from '@ionic-native/geolocation'
import Dexie from "dexie";
import {baseCommon} from '../common/baseCommon'
import {GroupsUtil} from '../common/CommonUtil'

@Component({
  templateUrl: 'app.html'
})

export class MyApp {

  rootPage: any = '';
  phone: any;
  password: any;
  latitude: any;
  longitude: any;
  message: any;
  ifsuccess: boolean = false;
  version: any;
  userid;
  public curPage;
  backButtonPressed: boolean = false; //用于判断返回键是否触发
  @ViewChild('myNav') nav: Nav;

  constructor(public platform: Platform,
              statusBar: StatusBar,
              splashScreen: SplashScreen,
              public storage: Storage,
              public http: Http,
              public keyBoard: Keyboard,
              public ionicApp: IonicApp,
              public toastCtrl: ToastController,
              public geolocation: Geolocation,
              public event: Events) {
    AppConfig.storage = this.storage;
    platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();
      this.registerBackButtonAction(); //注册返回按键事件
      /**
       * 检测用户本地缓存的status是否是logined，如果是，就使用缓存的phone以及password向后台发送login请求，若返回成功，则自动跳转至TabsPage。
       *
       * @param {any} phone
       * @param {any} password
       * @param {any} status
       * @memberof RegisterPage
       */
      this.storage.get('realPhone').then(val => {
        this.phone = val;
      });
      this.storage.get('phone').then(val => {
        this.userid = val;
      });
      this.storage.get('password').then(val => {
        this.password = val;
      });

      this.storage.get('version').then(val => {
        if (val == null) {
          this.storage.set('version', 1)
          this.version = 1;
        } else {
          this.version = val;
        }
      })


      this.storage.get('status').then(val => {
        console.log("1");
        // this.geolocation.getCurrentPosition().then((resp) => {
        //   this.latitude = resp.coords.latitude;
        //   this.longitude = resp.coords.longitude;
        //   console.log('地理坐标:' + this.latitude + " " + this.longitude)
        //   this.storage.set('x', this.longitude);
        //   this.storage.set('y', this.latitude);
        //   this.login(val)
        // }).catch((error) => {
        //   alert('位置信息有误！');
        //   console.log('Error getting location', error);
        //   this.login(val)
        // });
        this.login(val)
      })
    });
  }

  /**
   * 自动登录
   * @param val
   */
  login(val) {
    if (val == 'logined') {
      console.log("2");
      let headers = new Headers({
        'Content-Type': 'application/x-www-form-urlencoded',
      });

      let options = new RequestOptions({
        headers: headers,
      });

      let pramas: URLSearchParams = new URLSearchParams();
      pramas.set('realPhone', this.phone);
      pramas.set('password', this.password);
      pramas.set('x', this.longitude);
      pramas.set('y', this.latitude);

      let getData: any;


      this.http.post(AppConfig.httpLoc + '/login', pramas, options)
        .toPromise()
        .then(data => {
          getData = data.json();
          if (getData.message == "成功") {
            console.log('成功登陆!!')
            this.connect();
            this.storage.set('sessionID', getData.data[0]);
            // super.getInfo(this.http,getData.data[1],getData.data[0]);
            AppConfig.socket = io.connect(AppConfig.socketLoc);
            var event = this.event;
            this.auth(getData.data[0]);

            AppConfig.socket.on('connect', () => {
              console.log("Client has connected to the server!");
            });
            AppConfig.socket.on('message', data => {
              var nowGroupID = data.groupID;
              if (AppConfig.groups != null) {
                GroupsUtil.update(nowGroupID);
              }
              event.publish('message.received', data, Date.now());
            });

            AppConfig.socket.on('disconnect', () => {
              console.log("The client has disconnected!");
            });
            this.rootPage = TabsPage;
          } else {
            this.rootPage = IndexPage;
          }
        }, err => {
          console.log(err);
        })
    } else {
      this.rootPage = IndexPage;
    }
  }

  /**
   * 验证身份
   * @param sessionID
   */
  auth(sessionID) {
    console.log('进行了身份验证')
    var jsonObject = {
      message: sessionID
    };
    AppConfig.socket.emit('auth', jsonObject);
  }

  /**
   * 连接数据库
   */
  connect() {
    AppConfig.db = new Dexie(this.phone);
    AppConfig.db.version(1).stores({
      message: '++msgID,groupID,phone,username,date'
    });
    console.log('尝试连接')
  }

  //返回按键处理
  registerBackButtonAction() {
    this.platform.registerBackButtonAction(() => {
      console.log('点击了返回按键')
      // if (this.keyBoard.isOpen()) {
      //   this.keyBoard.close();
      // } else {
      let activeVC = this.nav.getActive();
      let page = activeVC.instance;
      //此处if是rootPage为登录页的情况，else是rootPage为TabsPage（如果不需要判断登录页的情况直接用else内的代码即可）
      let tabs = page.tabs;
      let activeNav = tabs.getSelected();
      if (!activeNav.canGoBack()) {
        console.log("viewctrl" + AppConfig.viewCtrl)
        if (AppConfig.viewCtrl == null) {
          console.log('检测到在 tab 页面的顶层点击了返回按钮。');
          this.showExit();
        } else {
          AppConfig.viewCtrl.dismiss()
        }
      } else {
        console.log('检测到当前 tab 弹出层的情况下点击了返回按钮。');
        activeNav.pop();
      }

      // }
    }, 1);
  }

  //双击退出提示框
  showExit() {
    if (this.backButtonPressed) { //当触发标志为true时，即2秒内双击返回按键则退出APP
      this.platform.exitApp();
    } else {
      this.toastCtrl.create({
        message: "再按一次退出应用",
        duration: 2000,
        position: 'bottom'
        //cssClass: 'toastcss' //修改样式（根据需要添加）
      }).present();
      this.backButtonPressed = true;
      setTimeout(() => this.backButtonPressed = false, 2000); //2秒内没有再次点击返回则将触发标志标记为false
    }
  }
}
